package com.wwcom.darteagle.view;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.wwcom.darteagle.R;
import com.wwcom.darteagle.ScoreEntryActivity;
import com.wwcom.darteagle.model.GlobalAppData;
import com.wwcom.darteagle.model.Match;
import com.wwcom.darteagle.model.MatchPlayer;
import com.wwcom.darteagle.model.Player;
import com.wwcom.darteagle.model.VisitScore;

public class LegHistoryView extends LinearLayout {
	//private data
	private Context context;
	private Match match;
	private VisitScoreArrayAdapter visitScoreAdaptor;
	private ListView visitScoreHistoryList;
	private HorizontalScrollView horizontalScrollView;
	private int colWidth;
	private int nCols;

	//constructors
	public LegHistoryView(Context context) {
		super(context);
		initialiseSelf(context);
	}

	public LegHistoryView(Context context, AttributeSet attrs) {
		super(context,attrs);
		initialiseSelf(context);
	}
	
	private void initialiseSelf(Context context) {
		this.context= context;
		View.inflate(context, R.layout.leghistoryview, this);

	    GlobalAppData gd= GlobalAppData.getSingletonInstance();
	    this.match= gd.match;
	    
    	horizontalScrollView= (HorizontalScrollView) this.findViewById(R.id.horizontal_scroll);
	    
    	//TODO: work in DP units correctly respecting device DPI
    	
	    //setup title rows
	    //float weight= (float)1.0/(float)match.getPlayers().size();
		int pixel= ((Activity) context).getWindowManager().getDefaultDisplay().getWidth();
	    if (pixel >= 960) { //xlarge-land
	    	pixel= 740;  //only use 50% display for this view
	    }
	    colWidth= pixel;
	    nCols= pixel / 200;
	    int nPlayers= match.getMatchPlayers().size(); 
	    if (nCols > nPlayers)
	    	nCols= nPlayers;
	    colWidth= pixel/nCols;	    	
	    if (nPlayers <= nCols) {
	    	horizontalScrollView.setFadingEdgeLength(0);
	    }
	    LinearLayout titles= (LinearLayout) this.findViewById(R.id.legScoreTitleNames);
	    List<TextView> tvl= new ArrayList<TextView>();
	    for (MatchPlayer mp : match.getMatchPlayers()) {
	    	Player p = mp.getPlayer();
			LayoutInflater inflator = ((Activity) context).getLayoutInflater();
			TextView tv = (TextView)inflator.inflate(R.layout.leghistoryview_player_name_textview, null);
	    	tv.setText(p.getName().toUpperCase());
	    	tv.setGravity(Gravity.CENTER_HORIZONTAL);
	    	tv.setTypeface(Typeface.DEFAULT_BOLD);
	    	LayoutParams lp= new LayoutParams(colWidth, LayoutParams.WRAP_CONTENT);
	    	tv.setLayoutParams(lp);
	    	tvl.add(tv);
	    	titles.addView(tv);
	    }
	    
	    LinearLayout titleScores= (LinearLayout) this.findViewById(R.id.legScoreTitleScores);
    	TextView tv= null;
    	int count= 0;
	    for (@SuppressWarnings("unused") MatchPlayer mp : match.getMatchPlayers()) {
			LayoutInflater inflator = ((Activity) context).getLayoutInflater();
	    	if (count == 0) {
				tv = (TextView)inflator.inflate(R.layout.leghistoryview_heading_textview_left, null);
	    	} else {
				tv = (TextView)inflator.inflate(R.layout.leghistoryview_heading_textview, null);	    		
	    	}
	    	tv.setText(context.getString(R.string.leghistory_score));
	    	LayoutParams lp= new LayoutParams((int) (colWidth*0.6), LayoutParams.WRAP_CONTENT);
	    	tv.setLayoutParams(lp);
	    	tv.setGravity(Gravity.CENTER_HORIZONTAL);
	    	tv.setTypeface(Typeface.DEFAULT_BOLD);
	    	titleScores.addView(tv);
	    	
	    	if (count == match.getMatchPlayers().size()-1) {
	    		tv = (TextView)inflator.inflate(R.layout.leghistoryview_heading_textview_right, null);	    		
	    	} else {
	    		tv = (TextView)inflator.inflate(R.layout.leghistoryview_heading_textview, null);
	    	}
	    	tv.setText(Integer.toString(match.getLegTarget()));
	    	LayoutParams lp2= new LayoutParams((int) (colWidth*0.4), LayoutParams.WRAP_CONTENT);
	    	tv.setLayoutParams(lp2);
	    	tv.setGravity(Gravity.CENTER_HORIZONTAL);
	    	tv.setTypeface(Typeface.DEFAULT_BOLD);
	    	titleScores.addView(tv);
	    	
	    	count++;
	    }
	    
	    visitScoreHistoryList= (ListView) this.findViewById(R.id.legHistoryViewList);
    	visitScoreAdaptor = new VisitScoreArrayAdapter(context,match.getLegHistory());
    	visitScoreHistoryList.setAdapter(visitScoreAdaptor);    	    	
	}
	
	
	public void updateVisitScore(Object o) {		
	  VisitScoreInfo vsi= (VisitScoreInfo)o;
	  Intent i= new Intent(context,ScoreEntryActivity.class);
	  i.putExtra(ScoreEntryActivity.VISIT_IND, vsi.getVisitInd());
	  i.putExtra(ScoreEntryActivity.PLAYER_IND, vsi.getPlayerInd());
  	  context.startActivity(i);	  
	}
	
	public void updateVisitScoreList() {
		visitScoreAdaptor.notifyDataSetChanged();				
		visitScoreHistoryList.smoothScrollToPosition(visitScoreHistoryList.getCount());	
	    if (match.getMatchPlayers().size() > nCols) {
	    	MatchPlayer cp= match.getLastPlayer();
	    	int cpInd= match.getMatchPlayers().indexOf(cp);
	    	horizontalScrollView.smoothScrollTo(cpInd * colWidth,
				horizontalScrollView.getScrollY());	
	    }
	}

	public void newVisitScoreList() {
		visitScoreAdaptor = new VisitScoreArrayAdapter(context,match.getLegHistory()); //NOTE: was context from external class
		visitScoreHistoryList.setAdapter(visitScoreAdaptor);
	}

    
    //private classes
	private static class VisitScoreViewHolder {
		protected TextView playerVisitScore;
		protected TextView playerLegScore;
	}
	
	private class VisitScoreInfo {
		private int visitInd;
		private int playerInd;
		public int getVisitInd() {
			return visitInd;
		}
		public int getPlayerInd() {
			return playerInd;
		}
		public VisitScoreInfo(int playerInd, int visitInd) {
			this.playerInd = playerInd;
			this.visitInd = visitInd;
		}
	}

	private class VisitScoreArrayAdapter extends ArrayAdapter<List<VisitScore>> {
    	private final List<List<VisitScore>> list;
    	private final Context context;

    	public VisitScoreArrayAdapter(Context context, List<List<VisitScore>> list) {
    		super(context, R.layout.leghistoryview_player_visitscore_textview, list);
    		this.context = context;
    		this.list = list;
    	}

    	@Override
    	public View getView(int position, View convertView, ViewGroup parent) {
    		View view = null;
			//if (convertView != null) {
			//	List<VisitScoreViewHolder> holder = (List<VisitScoreViewHolder>) convertView.getTag();
			//}
    		//if (convertView == null) {
    			view= new LinearLayout(context);
    			view.setPadding(0, 0, 0, 0);
    			List<VisitScoreViewHolder> viewHolder = new ArrayList<VisitScoreViewHolder>();
    			for (@SuppressWarnings("unused") MatchPlayer mp : match.getMatchPlayers()) {
    				VisitScoreViewHolder vsvh = new VisitScoreViewHolder();
    		    	LayoutParams lp= new LayoutParams((int) (colWidth*0.6), LayoutParams.WRAP_CONTENT);
    				LayoutInflater inflator = ((Activity) context).getLayoutInflater();    		    	
    				TextView tv = (TextView)inflator.inflate(R.layout.leghistoryview_player_visitscore_textview, null);
    		    	tv.setLayoutParams(lp);
    		    	tv.setGravity(Gravity.CENTER_HORIZONTAL);
    		    	tv.setText("");
    				tv.setTag(null);
					tv.setBackgroundColor(0x00000000); 
    		        //context menus
    		        ((Activity)context).registerForContextMenu(tv);
    		    	
    				((LinearLayout)view).addView(tv);
    				vsvh.playerVisitScore= tv;
    				tv = (TextView)inflator.inflate(R.layout.leghistoryview_player_legscore_textview, null);
    		    	lp= new LayoutParams((int) (colWidth*0.4), LayoutParams.WRAP_CONTENT);
    		    	tv.setLayoutParams(lp);
    		    	tv.setGravity(Gravity.CENTER_HORIZONTAL);
    		    	tv.setTypeface(Typeface.DEFAULT_BOLD);
    		    	tv.setText("");
    				tv.setTag(null);
    				((LinearLayout)view).addView(tv);
    				vsvh.playerLegScore= tv;
    		        //context menus
    		        ((Activity)context).registerForContextMenu(tv);
    				viewHolder.add(vsvh);
    			}    			    			
    			view.setTag(viewHolder);
    		//} else {
    		//	view = convertView;
        		/*List<VisitScoreViewHolder> holder = (List<VisitScoreViewHolder>) view.getTag();
    			for (int i= 0; i<match.getPlayers().size(); ++i) {
    				holder.get(i).playerVisitScore.setText("");
    				holder.get(i).playerVisitScore.setTag(null);
					holder.get(i).playerVisitScore.setBackgroundColor(0x00000000); 
    				holder.get(i).playerLegScore.setText("");
    				holder.get(i).playerLegScore.setTag(null);
    			} */   			    			
    		//}
    		List<VisitScore> vs= list.get(position);
    		@SuppressWarnings("unchecked")
			List<VisitScoreViewHolder> holder = (List<VisitScoreViewHolder>) view.getTag();
    		for (int i= 0; i<vs.size(); ++i) {
    			if (vs.size() > i && vs.get(i) != null)
    			{
    				VisitScoreInfo vsi= new VisitScoreInfo(i,position);
    				int visitScore= vs.get(i).getVisitScore();
    				holder.get(i).playerVisitScore.setText(Integer.toString(visitScore));
    				if (visitScore >= 180) {
    					holder.get(i).playerVisitScore.setBackgroundResource(R.drawable.yellow_180plus_sky); 
    				} else if (visitScore >= 140) {
    					holder.get(i).playerVisitScore.setBackgroundResource(R.drawable.yellow_140plus_sky); 
    				} else if (visitScore >= 100) {
    					holder.get(i).playerVisitScore.setBackgroundResource(R.drawable.yellow_100plus_sky); 
    				} else if (visitScore >= 60) {
    					holder.get(i).playerVisitScore.setBackgroundResource(R.drawable.yellow_60plus_sky); 
    				}
    				holder.get(i).playerVisitScore.setTag(vsi);
    				holder.get(i).playerLegScore.setText(Integer.toString(vs.get(i).getLegScore()));
    				holder.get(i).playerLegScore.setTag(vsi);
    			}
    		}
    		return view;
    	}
    }
	
	//context menu stuff
	public String getContextMenuTitle(Object o)
	{
  		VisitScoreInfo vsi= (VisitScoreInfo)o;
  		MatchPlayer matchPlayer= match.getMatchPlayers().get(vsi.getPlayerInd());
  		VisitScore vs= match.getVisitScore(matchPlayer, vsi.getVisitInd());
  		return matchPlayer.getPlayer().getName().toUpperCase() + " (" + vs.getVisitScore() +", "+vs.getLegScore()+")";
	}
}
